package com.ztjava.auth.service;

import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.HashKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.redis.Cache;
import com.jfinal.plugin.redis.Redis;
import com.ztjava.auth.model.AuthApp;
import com.ztjava.auth.model.AuthDept;
import com.ztjava.auth.model.AuthGroup;
import com.ztjava.auth.model.AuthGroupUser;
import com.ztjava.auth.model.AuthMessage;
import com.ztjava.auth.model.AuthRole;
import com.ztjava.auth.model.AuthRoleUser;
import com.ztjava.auth.model.AuthThird;
import com.ztjava.auth.model.AuthUser;
import com.ztjava.core.Constant;
import com.ztjava.core.base.BaseService;
import com.ztjava.core.bean.sub.MessageBean;
import com.ztjava.core.client.Client;
import com.ztjava.core.utiliy.StringUtil;
import com.ztjava.ext.auth.bean.AppSession;
import com.ztjava.ext.auth.bean.AuthSession;
import com.ztjava.ext.auth.tool.AuthTool;
import com.ztjava.plugin.event.EventKit;
import com.ztjava.plugin.event.EventTag;
import com.ztjava.plugin.event.core.RequestEvent;

public class AuthService extends BaseService {
	private static Logger logger = Logger.getLogger(AuthService.class);
	//其它模块帮助绑定手机号了
	public void bindingPhone(Integer user_id,String phone,HttpServletRequest request,String tokenType){
		AuthUser authUser = AuthUser.dao.findById(user_id);
		AuthUser is_repeat = AuthUser.dao.findFirst("select * from "+AuthUser.tablename+" where phone=? and portal=? and id<>?",phone,authUser.getStr("portal"),user_id);
		if(is_repeat!=null){
			//如出现同样手机号，则解除此账号手机号绑定。
			is_repeat.set("phone", null).set("phone_auth", "F").update();
			loadUserCache(is_repeat);
		}
		authUser.set("phone", phone);
		authUser.set("phone_auth", "T");
		authUser.update();
		loadUserCache(authUser);
		AuthTool.updateUserSession(request,tokenType, userToSession(authUser),null);
	}
	//解绑手机号
	public void unBindingPhone(Integer user_id,String phone,HttpServletRequest request,String tokenType){
		AuthUser authUser = AuthUser.dao.findById(user_id);
		authUser.set("phone", null).set("phone_auth", "F").update();
		loadUserCache(authUser);
		AuthTool.updateUserSession(request,tokenType, userToSession(authUser),null);
	}
	public boolean checkIsAuthPhone(Integer user_id){
		AuthUser authUser = AuthUser.dao.findById(user_id);
		if(authUser.getStr("phone_auth").equals("F")){
			return false;
		}else {
			return true;
		}
	}
	public boolean checkPhoneIsAuth(Integer user_id,String phone){
		Cache cache = Redis.use();
		if(cache.exists(Constant.R_PRE+"PHONEAUTH_"+user_id+"_"+phone)){
			return true;
		}
		AuthUser authUser = AuthUser.dao.findById(user_id);
		if(authUser.getStr("phone_auth").equals("F")){
			return false;
		}else {
			if(phone.equals(authUser.getStr("phone"))){
				return true;
			}else {
				return false;
			}
		}
	}
	public void setPhoneAuth(Integer user_id,String phone){
		Cache cache = Redis.use();
		cache.set(Constant.R_PRE+"PHONEAUTH_"+user_id+"_"+phone,phone);
		cache.expire(Constant.R_PRE+"PHONEAUTH_"+user_id+"_"+phone, 3600*24);
	}
	/*************
	 *Third分页
	**************/
	public Page<AuthThird> getThirdPage(Client client,Map<String,String[]> paramMap){
		String[][] param = new String[][]{
			new String[]{"portal",eq,"portal"}
			,new String[]{"source",like,"source"}
			,new String[]{"code",like,"code"}
			,new String[]{"enable_flag",eq,"enable_flag"}
		};
		Page<AuthThird> pd = AuthThird.dao.paginate(
				getParaToInt(paramMap, client.getPageNumber(), 1), 
				getParaToInt(paramMap,client.getPageSize(),20),
				"select *","from "+AuthThird.tablename+" where 1=1 " 				
				+ whereSql(paramMap,param)
				+ orderby(client, paramMap),whereParam(paramMap, param));
		changeBasedata(pd.getList()		, new String[]{"portal","AUTH_PORTAL"}		, new String[]{"enable_flag","ENABLE_FLAG"});
		return pd;
	}
	//有可能有重复的
	public AuthThird getUserThird(String portal,String source,Integer user_id){
		return AuthThird.dao.findFirst("select * from "+AuthThird.tablename+" where user_id=? and source=? and portal=? order by id desc",user_id,source,portal);
		
	}	
	
	public AuthThird getThirdByUserId(String portal,String source,Integer user_id){
		return AuthThird.dao.findFirst("select * from "+AuthThird.tablename+" where portal=? and source=? and user_id=?",portal,source,user_id);
	}
	
	public AuthThird getThirdByCode(String portal,String source,String code){
		AuthThird authThird = AuthThird.dao.findFirst("select * from "+AuthThird.tablename+" where source=? and code=? and portal=? order by id desc",source,code,portal);
		if(authThird==null){
			authThird = new AuthThird();
			authThird.set("portal", portal);
			authThird.set("source", source);
			authThird.set("code", code);
			authThird.set("last_login_time",new Timestamp(new Date().getTime()));
			authThird.save();
		}
		return authThird;
	}
	public AuthThird getThirdByCodeAndUnionid(String portal,String source,String code,String unionid){
		AuthThird authThird = AuthThird.dao.findFirst("select * from "+AuthThird.tablename+" where source=? and code=? and portal=? order by id desc",source,code,portal);
		if(authThird==null){
			authThird = new AuthThird();
			authThird.set("portal", portal);
			authThird.set("source", source);
			authThird.set("code", code);
			if(unionid!=null&&!unionid.equals("")){
				authThird.set("unionid",unionid);
				AuthThird unionThird = AuthThird.dao.findFirst("select * from "+AuthThird.tablename+" where unionid=? order by id desc",unionid);
				if(unionThird!=null){
					authThird.set("user_id", unionThird.getInt("user_id"));
				}
			}
			authThird.set("last_login_time",new Timestamp(new Date().getTime()));
			authThird.save();
		}
		return authThird;
	}
	//根据第三方信息创建或关联会员
	public AuthUser insertUserByThird(AuthThird authThird,Map<String,String> userMap){
		AuthUser authUser = null;
		if(authThird.get("unionid")!=null){
			AuthThird unionThird = AuthThird.dao.findFirst("select * from "+AuthThird.tablename
					+" where unionid=? and user_id is not null and id<>? order by id desc",
					authThird.getStr("unionid"),authThird.getInt("id"));
			if(unionThird!=null){
				authThird.set("user_id", unionThird.getInt("user_id"));
			}
		}
		if(authThird.get("user_id")==null){
			authUser = insertUser(Constant.P_MEMBER, userMap);
			authThird.set("user_id", authUser.getInt("id"));
		}else {
			authUser = AuthUser.dao.findById(authThird.getInt("user_id"));
		}
		authThird.update();
		//场景，微信邀请关注
		EventKit.postRemote(EventTag.AUTH_USER_BINDING, new RequestEvent(authThird.toRecord()));
		return authUser;
	}
	/***
	 * 新建用户
	 * @param portal
	 * @param userMap
	 * @return
	 */
	public AuthUser insertUser(String portal,Map<String,String> userMap){
		AuthUser authUser = new AuthUser();
		authUser.set("portal", portal.toUpperCase());
		String name = userMap.get("name");
		if(name!=null&&name.length()>30){
			name = name.substring(0,30);
		}
		if(name!=null){
			name = StringUtil.StringFilter(name);
		}
		//防止用户名为空
		if(name==null||name.equals("")){
			name = "会员"+StringUtil.getRandomString(8);
		}
		//防止姓名重复
		Cache cache = Redis.use();
		if(cache.hexists(Constant.R_USER+"_NAME", name)){
			name = name + StringUtil.getRandomString(4);
		}
		authUser.set("name", name);
		authUser.set("headimg", userMap.get("headimg"));
		if(userMap.get("password")!=null){
			authUser.set("password",HashKit.md5(userMap.get("password")).toUpperCase() );
		}
		authUser.set("username", userMap.get("username"));
		authUser.set("email", userMap.get("email"));
		if(userMap.get("email_auth")!=null){
			authUser.set("email_auth", userMap.get("email_auth"));
		}
		authUser.set("phone", userMap.get("phone"));
		if(userMap.get("phone_auth")!=null){
			authUser.set("phone_auth", userMap.get("phone_auth"));
		}
		authUser.save();
		authUser.set("uid", authUser.getInt("id")+10000).update();
		
		loadUserCache(authUser.getInt("id"));
		
		EventKit.postRemote(EventTag.AUTH_USER_INSERT, new RequestEvent(authUser.toRecord()));
		return authUser;
	}
	/***
	 * 检查用户是否重复
	 * @param portal
	 * @param type
	 * @param to
	 * @return
	 */
	public AuthUser checkUserAndType(String portal,String type, String to){
		AuthUser authUser = AuthUser.dao.findFirst("select * from "+AuthUser.tablename+" where "+type.toLowerCase()+"=? and portal=?",to,portal);
		
		return authUser;
	}
	
	
	/***
	 * AuthUser转AuthSession
	 * 
	 * @param authUser
	 * @return
	 */
	public AuthSession userToSession(AuthUser authUser) {
		AuthSession authSession = new AuthSession();
		authSession.setPortal(authUser.getStr("portal"));
		authSession.setId(authUser.getInt("id"));
		authSession.setUid(authUser.getInt("uid"));
		authSession.setUsername(authUser.getStr("username"));
		authSession.setName(authUser.getStr("name"));
		authSession.setPhone(authUser.getStr("phone"));
		authSession.setEmail(authUser.getStr("email"));
		authSession.setHeadimg(authUser.getStr("headimg"));
		authSession.setDept_id(authUser.getInt("dept_id"));
		//权限通过getUserMenu实现
		//组别通过setUserGroups实现
		return authSession;
	}
	/***
	 * 获取人员群组
	 * @param authSession
	 * @param portal
	 * @param request
	 */
	public void setUserGroups(AuthSession authSession,HttpServletRequest request,String tokenType){
		List<AuthGroupUser> groupUserList = AuthGroupUser.dao.find("select group_id from "+AuthGroupUser.tablename+" where user_id=? "
				+ "and group_id in (select id from "+AuthGroup.tablename+" where portal=? and enable_flag='T')",
				authSession.getId(),authSession.getPortal());
		String groupIds = "";
		for(int i=0;i<groupUserList.size();i++){
			groupIds = groupIds + groupUserList.get(i).getInt("group_id");
			if(i<(groupUserList.size()-1)){
				groupIds = groupIds + ",";
			}
			
		}
		authSession.setGroupIds(groupIds);
		AuthTool.updateUserSession(request,tokenType, authSession,null);
	}

	/***
	 * 获取用户菜单
	 * 
	 * @param authSession
	 * @param portal
	 * @param request
	 * @return
	 */
	public Map<String, JSONObject> getUserMenu(AuthSession authSession,HttpServletRequest request,String tokenType) {
		List<AuthRole> roleList = AuthRole.dao.find("select rights from "+ AuthRole.tablename
						+ " where id in (select role_id from "+ AuthRoleUser.tablename+ " where user_id=?) "
						+ "and rights is not null and enable_flag='T' and portal=?",authSession.getId(),authSession.getPortal());
		String rights = "";
		for (int i = 0, size = roleList.size(); i < size; i++) {
			rights = rights + roleList.get(i).getStr("rights");
		}
		Map<String, String> rightsMap = new HashMap<>();
		Cache cache = Redis.use();
		Map<String, JSONObject> menu = new LinkedHashMap<>();
		Map<String, JSONObject> portalRights = cache.hget(Constant.R_AUTH,authSession.getPortal());
		if (portalRights == null) {
			return menu;
		}
		boolean superRole = false;
		if (authSession.getName().equals("管理员")) {
			superRole = true;
		}
		for (String key : portalRights.keySet()) {
			JSONObject item = portalRights.get(key);
			if (superRole|| (item.get("is_default") != null && item.getString("is_default").equals(Constant.T))
					|| item.get("rights") == null|| rights.indexOf("," + item.getString("rights") + ",") > -1) {
				rightsMap.put(authSession.getPortal() + ":" + key, key);
				menu.put(key,checkChildren(item, rights, authSession.getPortal(), rightsMap, superRole));
				
			}
		}

		authSession.setRights(rightsMap);
		AuthTool.updateUserSession(request,tokenType, authSession,null);
		return menu;
	}

	/***
	 * 检查子菜单
	 * 
	 * @param item
	 * @param rights
	 * @param portal
	 * @param rightsMap
	 * @param superRole
	 * @return
	 */
	public JSONObject checkChildren(JSONObject item, String rights,
			String portal, Map<String, String> rightsMap, boolean superRole) {
		if (item.get("children") == null) {
			return item;
		}
		JSONArray newChildren = new JSONArray();
		JSONObject child;
		for (int i = 0; i < item.getJSONArray("children").size(); i++) {
			child = item.getJSONArray("children").getJSONObject(i);
			if (superRole|| (child.get("is_default") != null && child.getString("is_default").equals(Constant.T))
					|| child.get("rights") == null|| rights.indexOf("," + child.getString("rights") + ",") > -1) {
				if (child.get("rights") != null) {
					rightsMap.put(portal + ":" + child.getString("rights"),child.getString("rights"));
				}
				newChildren.add(checkChildren(item.getJSONArray("children").getJSONObject(i), rights, portal, rightsMap,superRole));
			}
		}
		if (newChildren.size() > 0) {
			item.put("children", newChildren);
		} else {
			item.remove("children");
		}
		return item;
	}

	/***
	 * 角色分页
	 * 
	 * @param client
	 * @param paramMap
	 * @return
	 */
	public Page<AuthRole> getRolePage(Client client,
			Map<String, String[]> paramMap) {
		String[][] param = new String[][] {
				new String[] { "portal", eq, "portal" },
				new String[] { "enable_flag", eq, "enable_flag" } };
		Page<AuthRole> pd = AuthRole.dao
				.paginate(getParaToInt(paramMap, client.getPageNumber(), 1),
						getParaToInt(paramMap, client.getPageSize(), 20),
						"select *", "from " + AuthRole.tablename+ " where 1=1 " + whereSql(paramMap, param)
								+ orderby(client, paramMap),
						whereParam(paramMap, param));
		changeBasedata(pd.getList(), new String[] { "portal", "AUTH_PORTAL" },
				new String[] { "enable_flag", "ENABLE_FLAG" });
		return pd;
	}

	/***
	 * 会员分页
	 * 
	 * @param client
	 * @param paramMap
	 * @return
	 */
	public Page<AuthUser> getUserPage(Client client,
			Map<String, String[]> paramMap) {
		String[][] param = new String[][] {
				new String[] { "portal", eq, "portal" },
				new String[] { "uid", eq, "uid" },
				new String[] { "username", like, "username" },
				new String[] { "name", like, "name" },
				new String[] { "phone", like, "phone" },
				new String[] {"phone_auth",eq,"phone_auth"},
				new String[] { "email", like, "email" },
				new String[] { "enable_flag", eq, "enable_flag" } };
		Page<AuthUser> pd = AuthUser.dao
				.paginate(getParaToInt(paramMap, client.getPageNumber(), 1),
						getParaToInt(paramMap, client.getPageSize(), 20),
						"select *", "from " + AuthUser.tablename
								+ " where 1=1 " + whereSql(paramMap, param)
								+ orderby(client, paramMap),
						whereParam(paramMap, param));
		changeBasedata(pd.getList(), new String[] { "portal", "AUTH_PORTAL" },
				new String[] { "dept_id", "AUTH_DEPT" }, new String[] {
						"enable_flag", "ENABLE_FLAG" });
		return pd;
	}

	/***
	 * 会员分页
	 * 
	 * @param client
	 * @param paramMap
	 * @return
	 */
	public Page<AuthGroup> getGroupPage(Client client,
			Map<String, String[]> paramMap) {
		String[][] param = new String[][] {
				new String[] { "portal", eq, "portal" },
				new String[] { "enable_flag", eq, "enable_flag" } };
		Page<AuthGroup> pd = AuthGroup.dao
				.paginate(getParaToInt(paramMap, client.getPageNumber(), 1),
						getParaToInt(paramMap, client.getPageSize(), 20),
						"select *", "from " + AuthGroup.tablename
								+ " where 1=1 " + whereSql(paramMap, param)
								+ orderby(client, paramMap),
						whereParam(paramMap, param));
		changeBasedata(pd.getList(), new String[] { "portal", "AUTH_PORTAL" },
				new String[] { "enable_flag", "ENABLE_FLAG" });
		return pd;
	}

	/***
	 * 角色人员
	 * 
	 * @param role_id
	 * @return
	 */
	public List<AuthUser> getRoleUserList(Integer role_id) {
		return AuthUser.dao.find("select * from " + AuthUser.tablename
				+ " where id in (select user_id from " + AuthRoleUser.tablename
				+ " where role_id=?)", role_id);
	}

	/***
	 * 非角色人员
	 * 
	 * @param role_id
	 * @param portal
	 * @return
	 */
	public List<AuthUser> getNotInRoleUserList(Integer role_id, String portal,
			String keyword, String ids) {
		String where = "";
		if (keyword != null && !keyword.equals("")) {
			where = " and (username like '%" + keyword + "%' or name like '%"
					+ keyword + "%') ";
		}
		if (ids != null && !ids.equals("")) {
			where = where + " and id not in (" + ids + ") ";
		}
		return AuthUser.dao.find("select * from " + AuthUser.tablename
				+ " where id not in (select user_id from "
				+ AuthRoleUser.tablename + " where role_id=?) and portal=? "
				+ where, role_id, portal);
	}

	/***
	 * 删除角色全部用户
	 * 
	 * @param id
	 */
	public void deleteRoleUser(Integer id) {
		Db.update("delete from " + AuthRoleUser.tablename + " where role_id=?",id);
	}

	/***
	 * 删除角色指定多个用户
	 * 
	 * @param role_id
	 * @param ids
	 */
	public void deleteRoleUserNotInStr(Integer role_id, String ids) {
		Db.update("delete from " + AuthRoleUser.tablename
				+ " where role_id=? and user_id not in (" + ids + ")", role_id);
	}

	/***
	 * 获取不在角色里的用户
	 * 
	 * @param role_id
	 * @param ids
	 * @return
	 */
	public List<AuthUser> getStrUserNotInRole(Integer role_id, String ids) {
		return AuthUser.dao.find("select id from " + AuthUser.tablename
				+ " where id in (" + ids
				+ ") and id not in (select user_id from "
				+ AuthRoleUser.tablename + " where role_id=? )", role_id);
	}

	/***
	 * 
	 * 获取非此用户角色列表
	 * @param user_id
	 * @return
	 */
	public List<AuthRole> getNotInUserRoleList(Integer user_id,String portal) {
		return AuthRole.dao.find("select * from " + AuthRole.tablename
				+ " where id not in (select role_id from "
				+ AuthRoleUser.tablename + " where user_id=?) and portal=?", user_id,portal);
	}

	/***
	 * 
	 * 获取用户角色列表
	 * @param user_id
	 * @param portal
	 * @return
	 */
	public List<AuthRole> getUserRoleList(Integer user_id, String portal) {
		return AuthRole.dao.find("select * from " + AuthRole.tablename
				+ " where id in (select role_id from " + AuthRoleUser.tablename
				+ " where user_id=?) and portal=?", user_id, portal);
	}

	/***
	 * 删除用户全部角色
	 * 
	 * @param user_id
	 */
	public void deleteUserRole(Integer user_id) {
		Db.update("delete from " + AuthRoleUser.tablename + " where user_id=?",
				user_id);
	}

	/***
	 * 获取组会员
	 * 
	 * @param group_id
	 * @return
	 */
	public List<AuthGroupUser> getGroupUserList(Integer group_id) {
		List<AuthGroupUser> userList = AuthGroupUser.dao.find(
				"select * from " + AuthGroupUser.tablename
						+ " where group_id=? order by id asc", group_id);
		changeUser(userList, new String[] { "user_id", "name" });
		return userList;
	}
	/***
	 * 同时在群组和部门里的用户
	 * @param group_id
	 * @param dept_id
	 * @return
	 */
	public List<AuthUser> getGroupAndDeptUserList(Integer group_id,Integer dept_id) {
		List<AuthUser> userList = AuthUser.dao.find(
				"select * from " + AuthUser.tablename
						+ " where id in (select user_id from "+AuthGroupUser.tablename+" where group_id=?) "
						+ "and dept_id=?  order by id asc", group_id,dept_id);
		return userList;
	}

	/***
	 * 删除组会员关联
	 */
	public void deleteGroupUser(Integer group_id) {
		Db.update("delete from " + AuthGroupUser.tablename
				+ " where group_id=?", group_id);
	}

	/***
	 * 更新群组人数
	 * 
	 * @param group_id
	 */
	public void updateGroupAmount(Integer group_id) {
		Db.update("update " + AuthGroup.tablename
				+ " set amount=(select count(id) from "
				+ AuthGroupUser.tablename + " where group_id=?) where id=?",
				group_id, group_id);
	}

	/***
	 * 移除全部部门人员
	 * 
	 * @param portal
	 * @param dept_id
	 */
	public void deleteUserDept(String portal, Integer dept_id) {
		Db.update("update " + AuthUser.tablename
				+ " set dept_id=null where portal=? and dept_id=?", portal,
				dept_id);
	}

	public void deleteUserDept(String portal, Integer dept_id, String ids) {
		Db.update("update "+ AuthUser.tablename
						+ " set dept_id=null where portal=? and dept_id=? and id not in ("+ ids + ")", portal, dept_id);
	}

	/***
	 * 批量赋予部门
	 * 
	 * @param portal
	 * @param dept_id
	 * @param ids
	 */
	public void insertUserDept(String portal, Integer dept_id, String ids) {
		Db.update("update " + AuthUser.tablename
				+ " set dept_id=? where portal=? and id in (" + ids + ")",
				dept_id, portal);
	}

	/***
	 * 获取无部门人员
	 * 
	 * @param portal
	 * @return
	 */
	public List<AuthUser> getNoDeptUserList(String portal, String keyword,
			String ids) {
		String where = "";
		if (keyword != null && !keyword.equals("")) {
			where = " and (username like '%" + keyword + "%' or name like '%"
					+ keyword + "%') ";
		}
		if (ids != null && !ids.equals("")) {
			where = where + " and id not in (" + ids + ") ";
		}
		return AuthUser.dao.find("select * from " + AuthUser.tablename
				+ " where portal=? and dept_id is null " + where
				+ " order by id desc", portal);
	}

	/***
	 * 获取部门人员
	 */
	public List<AuthUser> getDeptUserList(Integer dept_id) {
		return AuthUser.dao.find("select * from " + AuthUser.tablename
				+ " where dept_id=? order by id desc", dept_id);
	}

	/***
	 * 检查子部门
	 * 
	 * @param parent_id
	 * @return
	 */
	public boolean checkDeptChild(Integer parent_id) {
		if (AuthDept.dao.findFirst("select id from " + AuthDept.tablename
				+ " where parent_id=?", parent_id) != null) {
			return true;
		}
		return false;
	}

	public Page<AuthApp> getAppPage(Client client,
			Map<String, String[]> paramMap) {
		String[][] param = new String[][] {
				new String[] { "name", like, "name" },
				new String[] { "appid", like, "appid" },
				new String[] { "enable_flag", eq, "enable_flag" } };
		Page<AuthApp> pd = AuthApp.dao
				.paginate(
						getParaToInt(paramMap, client.getPageNumber(), 1),
						getParaToInt(paramMap, client.getPageSize(), 20),
						"select *",
						"from " + AuthApp.tablename + " where 1=1 "
								+ whereSql(paramMap, param)
								+ orderby(client, paramMap),
						whereParam(paramMap, param));
		changeBasedata(pd.getList(), new String[] { "enable_flag",
				"ENABLE_FLAG" });
		return pd;
	}
	/***
	 * 查找APP
	 * @param appid
	 * @param secretkey
	 * @return
	 */
	public AuthApp getAppByAuth(String appid,String secretkey){
		return AuthApp.dao.findFirst("select * from "+AuthApp.tablename+" where appid=? and secretkey=?",appid,secretkey);
	}
	

	/***
	 * 批量加载缓存
	 */
	public void loadUserCache() {
		List<AuthUser> userList = AuthUser.dao.find("select * from "+ AuthUser.tablename);
		Cache cache = Redis.use();
		cache.del(Constant.R_USER);
		for (int i = 0; i < userList.size(); i++) {
			cache.hset(Constant.R_USER, userList.get(i).getInt("id") + "",
					JSONObject.parseObject(userList.get(i).toJson()));
			cache.hset(Constant.R_USER+"_NAME", userList.get(i).getStr("name"),
					JSONObject.parseObject(userList.get(i).toJson()));
		}
		logger.info("用户信息缓存："+userList.size());
	}

	/***
	 * 单独加载缓存
	 * 
	 * @param user_id
	 */
	public void loadUserCache(Integer user_id) {
		AuthUser authUser = AuthUser.dao.findById(user_id);
		Cache cache = Redis.use();
		cache.hset(Constant.R_USER, authUser.getInt("id") + "",JSONObject.parse(authUser.toJson()));
		cache.hset(Constant.R_USER+"_NAME", authUser.getStr("name"),JSONObject.parseObject(authUser.toJson()));
	}
	public void loadUserCache(AuthUser authUser) {
		Cache cache = Redis.use();
		cache.hset(Constant.R_USER, authUser.getInt("id") + "",JSONObject.parse(authUser.toJson()));
		cache.hset(Constant.R_USER+"_NAME", authUser.getStr("name"),JSONObject.parseObject(authUser.toJson()));
	}
	
	public void loadAppCache(){
		Cache cache = Redis.use();
		List<AuthApp> appList = AuthApp.dao.find("select * from "+AuthApp.tablename+" where enable_flag='T' ");
		for(int i=0;i<appList.size();i++){
			AppSession appSession = new AppSession();
			appSession.setId(appList.get(i).getInt("id"));
			appSession.setAppid(appList.get(i).getStr("appid"));
			appSession.setName(appList.get(i).getStr("name"));
			appSession.setRights(appList.get(i).getStr("rights"));
			cache.hset(Constant.R_PRE+"AUTH:APP", appSession.getAppid(), appSession);
		}
	}
	
	public void insertMessage(MessageBean messageBean){
		AuthMessage authMessage = new AuthMessage();
		authMessage.set("model", messageBean.getModel());
		authMessage.set("type", messageBean.getType());
		authMessage.set("user_id", messageBean.getUser_id());
		authMessage.set("item_id", messageBean.getItem_id());
		authMessage.set("object_id", messageBean.getObject_id());
		if(messageBean.getContent().length()>300) {
			messageBean.setContent(messageBean.getContent().substring(0,300));
		}
		authMessage.set("content", messageBean.getContent());
		authMessage.set("create_user", messageBean.getCreate_user());
		authMessage.save();
	}
	
	public Page<AuthMessage> getMessagePage(Client client,Map<String, String[]> paramMap) {
		String[][] param = new String[][] {
				new String[] { "user_id", eq, "user_id" },
				new String[] { "is_read", eq, "is_read" },
				new String[] { "model", eq, "model" } };
		Page<AuthMessage> pd = AuthMessage.dao.paginate(
				getParaToInt(paramMap, client.getPageNumber(), 1),
				getParaToInt(paramMap, client.getPageSize(), 20),
				"select *", "from " + AuthMessage.tablename+ " where 1=1 " + 
				whereSql(paramMap, param)
				+ orderby(client, paramMap),whereParam(paramMap, param));
		changeBasedata(pd.getList(), new String[] { "is_read", "SHIFOU" });
		changeUser(pd.getList(), new String[]{"create_user","name"},
				new String[]{"create_user","headimg"});
		return pd;
		
	}
}
